package com.duapk.web.servlet;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URLDecoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.swetake.util.Qrcode;

/**
 * 二维码程序，通过网页展示二维码
 * 
 * @author yangfeng
 * 
 */
public class QRCodeShowServlet extends HttpServlet {
	
	private static Logger logger = LoggerFactory.getLogger(QRCodeShowServlet.class);

	private static final long serialVersionUID = 1316302207572570370L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String content = request.getQueryString();
		if (content == null || content.trim().length() == 0) {
			return;
		}
		content = URLDecoder.decode(content,"UTF-8");
		Qrcode qrCode = new Qrcode();
		qrCode.setQrcodeErrorCorrect('M');
		qrCode.setQrcodeEncodeMode('B');
		qrCode.setQrcodeVersion(7);
		BufferedImage bi = new BufferedImage(98, 98,
				BufferedImage.TYPE_BYTE_BINARY);
		Graphics2D g = bi.createGraphics();
		g.setBackground(Color.WHITE);
		g.clearRect(0, 0, 98, 98);
		g.setColor(Color.BLACK);
		byte[] d = null;
		try {
			d = content.getBytes("utf-8");
		} catch (Exception e) {
			logger.error("Encoding Error!",e);
		}

		// 限制最大字节数为120
		if (d != null) {
			if (d.length > 0 && d.length < 256) {
				boolean[][] s = qrCode.calQrcode(d);
				for (int i = 0; i < s.length; i++) {
					for (int j = 0; j < s.length; j++) {
						if (s[j][i]) {
							g.fillRect(j * 2 + 3, i * 2 + 3, 2, 2);
						}
					}
				}
			}
		}
		g.dispose();
		bi.flush();
		// 创建图片
		ImageIO.write(bi, "png", response.getOutputStream());
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
